/**
* LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
* // Hi I am Tony
* // 等待了5秒...
* // I am eating lunch
* // I am eating dinner
* // 等待了10秒...
* // I am eating junk food
*/

class LazyManClass {
  constructor(name) {
    // 创建队列用于保存要执行的函数
    this.queue = [];
    this.name = name;
    console.log(`Hi I am ${this.name}`);
    // 将next放入下一次消息循环
    setTimeout(() => {
      this.next();
    }, 0);
  }
  
  eat(food) {
    const fn = () => {
      console.log(`I am eating ${food}`);
      this.next();
    }
    this.queue.push(fn);
    return this;
  }

  sleep(wait) {
    const fn = () => {
      setTimeout(() => {
        console.log(`等待了${wait}秒...`)
        this.next();
      }, wait * 1000);
    }
    this.queue.push(fn);
    return this;
  }

  sleepFirst(wait) {
    const fn = () => {
      setTimeout(() => {
        console.log(`等待了${wait}秒...`)
        this.next();
      }, wait * 1000);
    }
    this.queue.unshift(fn);
    return this;
  }

  next() {
    const fn = this.queue.shift();
    fn && fn();
  }
}


// 测试------------------------------------------------
// function LazyMan(name) {
//   return new LazyManClass(name);
// }

new LazyManClass('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');